<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import type { VehicleTreeChildren } from "./index.vue";

const props = defineProps<{
  options: VehicleTreeChildren[];
  selectKey: string | null;
  autoExpandIds: string;
}>();
// interface Emits {
//   (event: "on-select", target: VehicleTreeChildren): void;
// }
interface Emits {
  // (event: "on-load"): void;
  (event: "on-select", target: VehicleTreeChildren): void;
}
const emits = defineEmits<Emits>();

const expandKey = ref<string[]>([]);
// const isBold = ref<boolean[]>([]);
watch(
  () => props.autoExpandIds,
  (newId: any) => {
    // console.log('需要展开车系',props.autoExpandIds)
    if (newId && !expandKey.value.includes(newId)) {
      expandKey.value.push(newId); // 如果新的ID不在expandKey中，添加它
    }
  }
);
onMounted(() => {
  if (Array.isArray(props.autoExpandIds) && !props.autoExpandIds.includes("")) {
    expandKey.value.push(props.autoExpandIds[0]);
  }
});
/**
 * 选中点击事件.
 * @param {VehicleTreeChildren} target
 */

function handleItemClick(target: VehicleTreeChildren) {
  if (expandKey.value.includes(target.id)) {
    expandKey.value = expandKey.value.filter((id: any) => id !== target.id);
  } else {
    expandKey.value.push(target.id);
  }
  emits("on-select", target);
}
</script>

<template>
  <ul class="p-0 py-1 m-0 list-none mxqls">
    <template v-for="item in props.options">
      <li @click.stop="() => handleItemClick(item)" class="lists">
        <div class="flex mxql Series">
          <span
            class="inline-block mt-4 w-2 h-4 mxql bg-[url('@/assets/temp/icons/forward.png')] bg-no-repeat bg-center"
            :class="{ 'rotate-90': expandKey.includes(item.id) }"
            v-if="item.childs.length"
          ></span>
          <span
            class="flex flex-col py-2 rounded-md cursor-pointer zileft Series"
            :class="{
              'text-primary': item.id === selectKey,
              'bg-primary/10': item.id === selectKey,
            }"
            :data-id="item.id"
          >
            <small class="text-sm">{{ item.name }}</small>
            <small class="text-sm text-gray-400">{{ item.nameEn }}</small>
          </span>
        </div>

        <Children
          :data-id="item.id"
          class="ml-6"
          :options="item.childs"
          :select-key="selectKey"
          :autoExpandIds="autoExpandIds"
          @on-select="handleItemClick"
          v-show="expandKey.includes(item.id)"
          v-if="item.childs?.length"
        />
      </li>
    </template>
  </ul>
</template>

<style lang="scss" scoped>
.zileft {
  padding-left: 0.5rem;
  padding-right: 1.5rem;
}
// .mxql {
//   margin-left: -1rem;
// }
.mxqls {
}
.font-bold {
  font-weight: bold;
}
.lists {
  margin-left: -2rem;
}
</style>
